import Layout from '../core/Layout'
import { UploadOutlined } from '@ant-design/icons';
import { Button, Input, Upload, Form, Select, message} from 'antd';
import { useState } from 'react';
import axios from 'axios';
import { API } from '../../config';
import { isAuth } from '../../helpers/auth';
import { useHistory } from 'react-router-dom';
import useGetCategories from '../../helpers/getCatgories';


function AddProduct() {
  const { token, user } = isAuth()
  const [file, setFile] = useState()
  const categories = useGetCategories()
  const props = {
    beforeUpload(file){
      setFile(file)
      return false
    }
  }
  const history = useHistory()
  const [form] = Form.useForm()
  const handelFinish = value => {
    const formData = new FormData()
    for (let attr in value){
      formData.append(attr, value[attr])
    }
    formData.append('photo' ,file)
    axios.post(`${API}/product/create/${ user._id }`, formData, {
      headers: { Authorization: `Bearer ${token}`}
    }).then(() => {
      message.success('商品添加成功')
      form.resetFields()
      history.push('/admin/dashboard')
    })
  }
  return (
    <Layout title='添加商品' subTitle='Are You Ready'>
      <Form initialValues={{category: '-1'}} onFinish={handelFinish} form={form}>
        <Form.Item>
          <Upload {...props}>
          <Button icon={<UploadOutlined />}>上传商品图片</Button>
          </Upload>
        </Form.Item>
        <Form.Item label='商品名称' name="name">
          <Input />
        </Form.Item>
        <Form.Item label='商品描述' name="description">
          <Input />
        </Form.Item>
        <Form.Item label='商品价格' name="price">
          <Input />
        </Form.Item>
        <Form.Item label='所属分类' name="category">
          <Select>
            <Select.Option value='-1'>请选择分类</Select.Option>
            {categories.map(category => (
              <Select.Option key={category._id} value={category._id}>{category.name}</Select.Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item label='是否运输' name="shipping">
          <Select>
            <Select.Option value='0'>否</Select.Option>
            <Select.Option value='1'>是</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item label='商品数量' name="quantity">
          <Input />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">添加</Button>
        </Form.Item>
      </Form>
    </Layout>
    )
}

export default AddProduct
